package org.linlinjava.litemall.admin.wx.handler;

import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.linlinjava.litemall.admin.service.WxMsgReplyService;
import org.linlinjava.litemall.core.template.WxMpMsgTemplateService;
import org.linlinjava.litemall.db.domain.WxUser;
import org.linlinjava.litemall.db.service.WxUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author Binary Wang
 */
@Component
public class SubscribeHandler extends AbstractHandler {
	
	@Autowired
	private WxUserService wxUserService;
    @Autowired
    private WxMsgReplyService wxMsgReplyService;
    @Autowired
    private WxMpMsgTemplateService wxMsgTemplateService;

  @Override
  public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, Map<String, Object> context, WxMpService wxMpService,
                                  WxSessionManager sessionManager) throws WxErrorException {

    this.logger.info("新关注用户 OPENID: " + wxMessage.getFromUser() + "，事件：" + wxMessage.getEventKey());

    // 获取微信用户基本信息
    WxMpUser userWxInfo = wxMpService.getUserService().userInfo(wxMessage.getFromUser());
    Boolean newANDold = false;//是否新用户
    if (userWxInfo != null) {
      //保存用户
      //先查询是否已存在
      WxUser wxUser = wxUserService.getOneUser(userWxInfo.getOpenId());
      if(wxUser == null) {
    	 wxUserService.add(userWxInfo);
    	 newANDold = true;
      }else {
    	 wxUser.setSubscribe(!wxUser.getSubscribe());
    	 wxUserService.update(wxUser);
      }
      //匹配回复规则
      wxMsgReplyService.tryAutoReply(wxMessage.getFromUser(),wxMessage.getEvent());
      
      wxMsgTemplateService.activeSend(userWxInfo,"subscribe", newANDold,null,null);
    }
    /*
    if (!StringUtils.isEmpty(wxMessage.getEventKey())) {// 处理特殊事件，如用户扫描带参二维码关注
        msgReplyService.tryAutoReply(true, wxMessage.getFromUser(), wxMessage.getEventKey());
    }*/

    return null;
  }

  /**
   * 处理特殊请求，比如如果是扫码进来的，可以做相应处理
   */
  protected WxMpXmlOutMessage handleSpecial(WxMpXmlMessage wxMessage) throws Exception {
    //TODO
    return null;
  }

}
